<template>
  <div>
    <el-upload
      :action="$http.adornUrl(url)"
      :headers="{Authorization: $cookie.get('Authorization')}"
      list-type="picture-card"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :file-list="imageList"
      :before-upload="beforeAvatarUpload"
      :limit="10"
      :on-exceed="handleExceed">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        dialogImageUrl: '',
        dialogVisible: false,
        resourcesUrl: window.SITE_CONFIG.resourcesUrl
      }
    },
    props: {
      value: {
        default: '',
        type: String
      },
      size: {
        default: 1024*1024*10,
        type: Number
      },
      count: {
        default: 10,
        type: Number
      },
      url: {
        default: '/admin/file/upload/element',
        type: String
      }
    },
    computed: {
      imageList () {
        let res = []
        if (this.value) {
          let imageArray = this.value.split(',')
          for (let i = 0; i < imageArray.length; i++) {
            res.push({url: this.resourcesUrl + imageArray[i], response: imageArray[i]})
          }
        }
        this.$emit('input', this.value)
        return res
      }
    },
    methods: {
      // 图片上传
      handleUploadSuccess (response, file, fileList) {
        let pics = fileList.map(file => {
          return file.response
        }).join(',')
        this.$emit('input', pics)
      },
      // 限制图片上传大小
      beforeAvatarUpload (file) {
        const isLt2M = file.size<this.size
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 10MB!')
        }
        return isLt2M
      },
      handleRemove (file, fileList) {
        let pics = fileList.map(file => {
          return file.response
        }).join(',')
        this.$emit('input', pics)
      },
      handlePictureCardPreview (file) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      },
      handleExceed(files, fileList) {
        this.$message.warning('当前限制选择 10 个文件');
      },    
    }
  }
</script>

<style lang="scss">
// .avue-upload__avatar, .avue-upload__icon, .el-upload--picture-card, .el-upload-list--picture-card .el-upload-list__item {
//     width: 300px;
//     height: auto;
//     line-height: auto;
// }

// .el-upload-list--picture-card .el-upload-list__item {
//     overflow: hidden;
//     background-color: #fff;
//     border: 1px solid #c0ccda;
//     border-radius: 6px;
//     -webkit-box-sizing: border-box;
//     box-sizing: border-box;
//     width: auto;
//     margin: 0 8px 0 0;
//     display: inline-block;
// }
// .el-upload.el-upload--picture-card {
//     width: 180px;
//     height: 180px;
//     line-height: 180px;
// }
</style>